package com.framework.bdf4j.comm.persist;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.framework.bdf4j.comm.SpringContextHolder;
import com.framework.bdf4j.comm.web.WebUtil;
import com.framework.bdf4j.sysadm.entity.SysRole;
import com.framework.bdf4j.sysadm.service.SysRoleService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 默认data scope 判断处理器
 */
public class ScaDefaultDatascopeHandle implements DataScopeHandle {

    private SysRoleService sysRoleService = null;

    /**
     * 计算用户数据权限
     * 
     * @param deptList
     * @return
     */
    @Override
    public Boolean calcScope(List<Integer> deptList) {
        sysRoleService = SpringContextHolder.getBean(SysRoleService.class);

        List<Integer> roleIdList = WebUtil.getHttpCurrentRoles();
        // 当前用户的角色为空
        if (CollectionUtil.isEmpty(roleIdList)) {
            return false;
        }
        SysRole role =
            sysRoleService.listByIds(roleIdList).stream().min(Comparator.comparingInt(SysRole::getDsType)).get();
        // 角色有可能已经删除了
        if (role == null) {
            return false;
        }
        Integer deptId = WebUtil.getHttpCurrentUserDptId();
        Integer dsType = role.getDsType();
        // 查询全部
        if (DataScopeTypeEnum.ALL.getType() == dsType) {
            return true;
        }
        // 自定义
        if (DataScopeTypeEnum.CUSTOM.getType() == dsType) {
            String dsScope = role.getDsScope();
            deptList.addAll(
                Arrays.stream(dsScope.split(StrUtil.COMMA)).map(Integer::parseInt).collect(Collectors.toList()));
        }
        // 查询本级及其下级
        if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
            List<Integer> deptIdList = null;
            deptList.addAll(deptIdList);
        }
        // 只查询本级
        if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
            deptList.add(deptId);
        }
        return false;
    }

}
